package com.io.commonlib.helper

import java.util.*

/**
 * Description: 数据处理工具类
 * 2020-02-11 10:00
 * @author LiuMin
 */
class DataHelper {
    /**
     * 字节数组转16进制
     * @param bytes 需要转换的byte数组
     * @return  转换后的Hex字符串
     */
    fun bytesToHex(bytes: ByteArray): String {
        val sb = StringBuffer()
        for (i in bytes.indices) {
            val value0 = bytes[i].toInt() and 0xFF
            val hex = Integer.toHexString(value0)
            if (hex.length < 2) {
                sb.append(0)
            }
            sb.append(hex)
        }
        return sb.toString()
    }

    /**
     * hex字符串转byte数组
     * @param inHex 待转换的Hex字符串
     * @return  转换后的byte数组结果
     */
    fun hexToByteArray(inHex: String): ByteArray {
        var inHex = inHex
        var hexlen = inHex.length
        val result: ByteArray
        if (hexlen % 2 == 1) {
            //奇数
            hexlen++
            result = ByteArray(hexlen / 2)
            inHex = "0$inHex"
        } else {
            //偶数
            result = ByteArray(hexlen / 2)
        }
        var j = 0
        var i = 0
        while (i < hexlen) {
            result[j] = hexToByte(inHex.substring(i, i + 2))
            j++
            i += 2
        }
        return result
    }

    /**
     * Hex字符串转byte
     * @param inHex 待转换的Hex字符串
     * @return  转换后的byte
     */
    fun hexToByte(inHex: String): Byte {
        return inHex.toInt(16).toByte()
    }

    /**
     * 判断字符串是否是十六进制字符串
     */
    fun isHexNumber(str: String): Boolean {
        val strNew = str.toLowerCase(Locale.ENGLISH)
        for (i in 0 until strNew.length) {
            val cc = str[i]
            if (cc != '0' && cc != '1' && cc != '2' && cc != '3' && cc != '4' && cc != '5'
                && cc != '6' && cc != '7' && cc != '8' && cc != '9' && cc != 'a' && cc != 'b'
                && cc != 'c' && cc != 'c' && cc != 'd' && cc != 'e' && cc != 'f'
            ) {
                return false;
            }
        }
        return true
    }

    /**
     * 将字符串做逆序处理
     * @param sourceStr
     */
    fun reverseString(sourceStr: String): String {
        var result = ""
        if (sourceStr.isNotEmpty()) {
            val sourceBytes = sourceStr.toByteArray()
            val targetBytes = ByteArray(sourceBytes.size)
            for (i in 0 until sourceStr.length) {
                targetBytes[sourceStr.length - i - 1] = sourceBytes[i]
            }
            result = String(targetBytes)
        }
        return result
    }
}